package com.pay.ioopos.fragment;

import static com.pay.ioopos.App.DEV_IS_306_308;
import static com.pay.ioopos.App.DEV_IS_FACE;
import static com.pay.ioopos.App.DEV_IS_K12;
import static com.pay.ioopos.AppUtils.speak;
import static com.pay.ioopos.AppUtils.toast;
import static com.pay.ioopos.Constants.INTENT_PARAM_AMOUNT;
import static com.pay.ioopos.Constants.INTENT_PARAM_CASE;
import static com.pay.ioopos.Constants.INTENT_PARAM_CODE;
import static com.pay.ioopos.support.scan.weixin.MyWxPayFace.IS_OFFLINE;
import static com.pay.ioopos.widget.Tip.TipType.WAIT;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.pay.ioopos.KeyCodeFactory;
import com.pay.ioopos.KeyInfo;
import com.pay.ioopos.R;
import com.pay.ioopos.display.CustomerHolder;
import com.pay.ioopos.fragment.support.BindState;
import com.pay.ioopos.fragment.support.CheckInState;
import com.pay.ioopos.fragment.support.Scheduled;
import com.pay.ioopos.sqlite.SettingStore;
import com.pay.ioopos.sqlite.StoreFactory;
import com.pay.ioopos.support.card.CardFactory;
import com.pay.ioopos.support.scan.ScanCase;
import com.pay.ioopos.support.scan.ScanLife;
import com.pay.ioopos.support.scan.ScanListener;
import com.pay.ioopos.support.scan.s1601.ScanS1601Qrcode;
import com.pay.ioopos.support.scan.sp308.ScanCamera;
import com.pay.ioopos.support.scan.weixin.ScanWxOfflineFace;
import com.pay.ioopos.support.scan.weixin.ScanWxOfflineQrcode;
import com.pay.ioopos.support.scan.weixin.ScanWxOnlineFace;
import com.pay.ioopos.support.scan.weixin.ScanWxOnlineQrcode;
import com.pay.ioopos.support.serialport.Cmd;
import com.pay.ioopos.support.serialport.CmdCase;
import com.pay.ioopos.support.serialport.OnMutipleListener;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 等待用户支付，扫码、刷Id卡、刷脸
 * @author    Moyq5
 * @since  2020/3/30 12:05
 */
public class PayScanFragment extends TipHorizontalFragment implements BindState, CheckInState, Scheduled, View.OnKeyListener {
    private final String amount;
    private final ScanListener listener;
    public PayScanFragment() {
        super(WAIT, R.string.pay_wait);
        amount = null;
        listener = new ScanListener() {
            @Override
            public boolean onScan(Intent intent) {
                return false;
            }

            @Override
            public void onError(String msg) {

            }
        };
    }

    public PayScanFragment(String amount, ScanListener listener) {
        super(WAIT, R.string.pay_wait);
        this.amount = amount;
        this.listener = proxyListener(listener);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        if (null == view) {
            return null;
        }
        view.setFocusable(true);
        view.setOnKeyListener(this);
        view.setKeepScreenOn(true);
        view.requestFocus();
        return view;
    }

    @Override
    protected void execute() throws Exception {
        try {
            if (null == amount || new BigDecimal(amount).compareTo(BigDecimal.ZERO) != 1) {
                throw new NumberFormatException();
            }
        } catch (NumberFormatException e) {
            listener.onError("金额错误：" + amount);
            return;
        }

        ScanLife life = new ScanLife(createScanCases());
        life.setScanListener(listener);
        life.bindToLifecycle(this);

        speak("请支付" + amount + "元");
        customerHolder().setAmount(amount);

        SettingStore store = StoreFactory.settingStore();

        if (DEV_IS_FACE && store.getSwitchFacePay() && store.getSwitchFaceAutoScan()) {
            customerHolder().payFace();
            return;
        }

        customerHolder().payWait();
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() != KeyEvent.ACTION_UP) {
            return true;
        }

        KeyInfo keyInfo = KeyCodeFactory.getKeyInfo(keyCode);
        if (null == keyInfo) {
            return true;
        }

        switch (keyInfo) {
            case KEY_ENTER:
            case KEY_CANCEL:
            case KEY_MENU:
            case KEY_SEARCH:
                return false;
        }

        return true;
    }

    public ScanListener proxyListener(ScanListener listener) {
        return new ScanListener() {

            @Override
            public void onError(String detail) {
                speak("支付失败");
                toast(detail);
                customerHolder().payStatus(CustomerHolder.PayProccess.FAIL, amount, detail);
                listener.onError("支付失败");
            }

            @Override
            public boolean onScan(Intent intent) {
                intent.putExtra(INTENT_PARAM_AMOUNT, amount);
                return listener.onScan(intent);
            }
        };
    }

    private List<ScanCase> createScanCases() {
        SettingStore store = StoreFactory.settingStore();

        List<ScanCase> cases = new ArrayList<>();

        // 外接扫码器s1601
        cases.add(new ScanS1601Qrcode(getContext()));

        // 串口读卡或者扫码
        int flag = 0;
        if (store.getSwitchNfcPay()) {
            flag |= 1;
        }
        if (store.getSwitchScanPay()) {
            flag |= 2;
        }
        CmdCase cmdCase = CardFactory.getCmdCase();
        if (flag > 0 && null != cmdCase) {
            Cmd cmd = CardFactory.uidOrQrcodeRead(flag, new OnMutipleListener() {
                @Override
                public Cmd onSuccess(int flag, String value) {
                    Intent intent = new Intent();
                    intent.putExtra(INTENT_PARAM_CASE, flag == 1 ? ScanCase.NFC: ScanCase.QRCODE);
                    intent.putExtra(INTENT_PARAM_CODE, value);
                    listener.onScan(intent);
                    return null;
                }

                @Override
                public Cmd onFail(int flag, String value) {
                    listener.onError(value);
                    return null;
                }
            }, cmdCase);
            if (null != cmd) {
                cmdCase.setRootCmd(cmd);
                cases.add(cmdCase);
            }
        }

        if (DEV_IS_306_308) {
            if (store.getSwitchScanPay()) {
                cases.add(new ScanCamera());
            }
            return cases;
        }

        if (!DEV_IS_FACE || !store.getSwitchFacePay()) {
            return cases;
        }

        // 微信在线、离线刷脸
        if (IS_OFFLINE) {
            if (!DEV_IS_K12) {
                cases.add(new ScanWxOfflineQrcode());// 影响刷脸效率, 所以仅限于非306pro的其它设备
            }
            ScanWxOfflineFace scanWxFace = new ScanWxOfflineFace(getContext(), amount);
            customerHolder().setScanFace(scanWxFace);
            cases.add(scanWxFace);
        } else {
            if (!DEV_IS_K12) {
                cases.add(new ScanWxOnlineQrcode());// 影响刷脸效率, 所以仅限于非306pro的其它设备
            }
            ScanWxOnlineFace scanWxFace = new ScanWxOnlineFace(getContext(), amount);
            customerHolder().setScanFace(scanWxFace);
            cases.add(scanWxFace);
        }

        return  cases;

    }

}
